<template>
<div class="app-container calendar-list-container">
  <div class="filter-container">
    <el-input v-if="this.userType === 1" @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="平台编号" v-model="platformId"> </el-input>
    <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="用户编号" v-model="listQuery.customerId"> </el-input>
    <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="商户客户编号" v-model="listQuery.merchantId"> </el-input>
    <el-button class="filter-item" type="primary" icon="search" @click="handleFilter">搜索</el-button>
    <el-button class="filter-item"  v-if="merchantManager_btn_add"  style="margin-left: 10px;" @click="handleCreate" type="primary" icon="edit">添加</el-button>
    <el-button class="filter-item"   style="margin-left: 10px;color:#999999; background-color:white;border-color:#ececec" @click="handleCreateSecect" type="primary" icon="edit">设置</el-button>
  </div>
  <el-dialog title="选择" :visible.sync="dialogSelectTableVisible"
  :before-close="handleClose"
>
  <el-checkbox-group v-model="checkList">
    <el-checkbox label="merchantId">商户客户编号</el-checkbox>
    <el-checkbox label="platformId">平台编号</el-checkbox>
    <el-checkbox label="merchantName">商户名称</el-checkbox>
    <el-checkbox label="owner" >归属人</el-checkbox>
    <el-checkbox label="thirdNo" >第三方会员编号</el-checkbox>
    <el-checkbox label="merType">商户类型</el-checkbox>
    <el-checkbox label="phone">联系电话</el-checkbox>
    <el-checkbox label="companyAddress">企业地址</el-checkbox>
    <el-checkbox label="authenticationStatus" >认证状态</el-checkbox>
    <el-checkbox label="status" >账户状态</el-checkbox>
    <el-checkbox label="createTime" >创建时间</el-checkbox>
  </el-checkbox-group>
</el-dialog>
  <el-table :key='tableKey' :data="list" v-loading.body="listLoading" border fit highlight-current-row style="width: 100%">
    <el-table-column  align="center" :key="fruit" v-for='fruit in formThead' :label="formTheadName[fruit]" :width="formTheadWidth[fruit]">
      <template slot-scope="scope">
        <div v-if = "fruit === 'authenticationStatus'" width="190" >
          <span v-if="scope.row.authenticationStatus === '00'">未认证</span>
          <span v-if="scope.row.authenticationStatus === '01'">无需认证</span>
          <span v-if="scope.row.authenticationStatus === '02'">认证成功</span>
          <span v-if="scope.row.authenticationStatus === '03'">认证失败</span>
        </div>
        <div v-else-if = "fruit === 'merType'" >
          <span v-if="scope.row.merType === '00'">普通商户</span>
            <span v-if="scope.row.merType === '01'">子商户</span>
        </div>
        <div v-else >
          {{scope.row[fruit]}}
        </div>
      </template>
    </el-table-column>


    <!-- <el-table-column width="160" align="center" label="商户客户编号"> <template scope="scope">
          <span>{{scope.row.merchantId}}</span>
        </template> </el-table-column>
    <el-table-column width="110" align="center" label="平台编号"> <template scope="scope">
        <span>{{scope.row.platformId}}</span>
      </template> </el-table-column>
    <el-table-column width="110" align="center" label="商户名称"> <template scope="scope">
            <span>{{scope.row.merchantName}}</span>
          </template> </el-table-column>
    <el-table-column width="110" align="center" label="归属人"> <template scope="scope">
            <span>{{scope.row.owner}}</span>
          </template> </el-table-column>
    <el-table-column width="110" align="center" label="第三方会员编号"> <template scope="scope">
            <span>{{scope.row.thirdNo}}</span>
          </template> </el-table-column>
    <el-table-column width="110" align="center" label="商户类型"> <template scope="scope">
            <span v-if="scope.row.merType === '00'">普通商户</span>
            <span v-if="scope.row.merType === '01'">子商户</span>
          </template> </el-table-column>
    <el-table-column width="110" align="center" label="联系电话"> <template scope="scope">
            <span>{{scope.row.phone}}</span>
          </template> </el-table-column>
    <el-table-column width="110" align="center" label="企业地址"> <template scope="scope">
            <span>{{scope.row.companyAddress}}</span>
          </template> </el-table-column>
    <el-table-column width="160" align="center" label="认证状态"> <template scope="scope">
            <span v-if="scope.row.authenticationStatus === '00'">未认证</span>
            <span v-if="scope.row.authenticationStatus === '01'">无需认证</span>
            <span v-if="scope.row.authenticationStatus === '02'">认证成功</span>
            <span v-if="scope.row.authenticationStatus === '03'">认证失败</span>
          </template> </el-table-column>
    <el-table-column width="110" align="center" label="账户状态"> <template scope="scope">
            <span v-if="scope.row.status === '00'">正常</span>
            <span v-if="scope.row.status === '01'">冻结</span>
          </template> </el-table-column>
    <el-table-column width="160" align="center" label="创建时间"> <template scope="scope">
            <span>{{scope.row.createTime}}</span>
          </template> </el-table-column> -->
    <el-table-column align="center" label="操作" width="300"> <template scope="scope">
        <el-button size="small" type="success" @click="merchantDetail(scope.row)">详情</el-button>
        <el-button v-if="merchantManager_btn_update" size="small" type="success" @click="handleUpdate(scope.row)">编辑</el-button>
        <el-button v-if="merchantManager_btn_del" size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
      </template> </el-table-column>
  </el-table>
  <div v-show="!listLoading" class="pagination-container">
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
  </div>
  <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
    <el-form :model="form" ref="form" :rules="rules">
      <el-form-item label="商户名称" :label-width="formLabelWidth" prop="merchantName">
        <el-input style="width:200px;" v-model="form.merchantName" placeholder="请输入商户名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="企业名称" :label-width="formLabelWidth" prop="companyName">
        <el-input style="width:200px;" v-model="form.companyName" placeholder="请输入企业名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="地址" :label-width="formLabelWidth">
        <el-cascader :options="areaList" v-model="form.selectedAreas" @change="handleSelectArea" placeholder="请选择商户地址"></el-cascader>
      </el-form-item> 
      <el-form-item label="经营范围" :label-width="formLabelWidth">
        <el-input style="width:200px;" v-model="form.businessScope" placeholder="请输入经营范围" type="textarea" :rows="2" clearable></el-input>
      </el-form-item>
      <el-form-item label="工商注册号" :label-width="formLabelWidth">
        <el-input style="width:200px;" v-model="form.businessNo" placeholder="请输入工商注册号" clearable></el-input>
      </el-form-item>
      <el-form-item label="法人姓名" :label-width="formLabelWidth">
        <el-input style="width:200px;" v-model="form.legalPersonName" placeholder="请输入法人姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="法人证件类型" :label-width="formLabelWidth">
        <el-select v-model="form.legalPersonCredType" placeholder="请选择证件类型">
          <el-option v-for="item in cardTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="法人证件号码" :label-width="formLabelWidth">
        <el-input style="width:200px;" v-model="form.legalPersonCredNo" placeholder="请输入法人证件号码" clearable></el-input>
      </el-form-item>
      <el-form-item label="联系电话" :label-width="formLabelWidth">
        <el-input style="width:200px;" v-model="form.phone" placeholder="请输入联系电话" clearable></el-input>
      </el-form-item>
      <el-form-item label="商户类型" :label-width="formLabelWidth">
        <el-select v-model="form.merType" placeholder="请选择商户类型" @change="merTypeChange">
          <el-option v-for="item in merTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="父商户" :label-width="formLabelWidth" v-if="parentVisible === true">
        <el-select v-model="form.parentMerId" placeholder="请选择父商户" >
          <el-option v-for="item in commonMerchant" :key="item.merchantId" :label="item.merchantName" :value="item.merchantId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="企业座机" :label-width="formLabelWidth">
        <el-input style="width:200px;" v-model="form.mobile" placeholder="请输入企业座机" clearable></el-input>
      </el-form-item>
      <el-form-item label="企业传真" :label-width="formLabelWidth">
        <el-input style="width:200px;" v-model="form.fax" placeholder="请输入企业传真" clearable></el-input>
      </el-form-item>
      <el-form-item label="企业网址" :label-width="formLabelWidth">
        <el-input style="width:200px;" v-model="form.httpAddress" placeholder="请输入企业网址" clearable></el-input>
      </el-form-item>
      <el-form-item label="注册资金" :label-width="formLabelWidth">
        <el-input style="width:200px;" v-model="form.registeredCapital" placeholder="请输入注册资金" clearable></el-input>
      </el-form-item>
      <el-form-item label="企业地址" :label-width="formLabelWidth">
        <el-input style="width:200px;" v-model="form.companyAddress" placeholder="请输入企业地址" clearable></el-input>
      </el-form-item>
      <el-form-item label="营业执照" :label-width="formLabelWidth">
        <div class="imgSrc" @click="upIdNegativeUrl">
          <img v-if="form.businessLicence" :src="form.businessLicence" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </div>
        <input type="file" name="file" id="upload_idNegative" @change="upIdNegative" accept="image/png,image/gif" style="display: none">
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button v-if="dialogStatus==='create'" type="primary" @click="create('form')">确 定</el-button>
      <el-button v-else type="primary" @click="update('form')">确 定</el-button>
    </div>
  </el-dialog>

</div>
</template>

<script>
import axios from 'axios'
import { page, addObj, putObj, delObj } from '@/api/crm/customers/merchantBase'
import { addOrUpdate, queryObj } from '@/api/crm/customers/personalBase'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { fetchArea } from '@/api/crm/area/index'

export default {
  name: 'personals',
  data() {
    return {
      platformId: undefined,
      listQuery: {
        page: 1,
        limit: 10,
        platformId: undefined,
        customerId: undefined,
        merchantId: undefined
      },
      queryObjdata: {
        userId: undefined,
        platformId: undefined,
        pageTag: 'merchantBase'
      },
      addOrUpdate: {
        userId: undefined,
        platformId: undefined,
        pageTag: 'merchantBase',
        columns: undefined
      },
      formTheadName: {
        merchantId: '商户客户编号',
        platformId: '平台编号',
        merchantName: '商户名称',
        owner: '归属人',
        thirdNo: '第三方会员编号',
        merType: '商户类型',
        phone: '联系电话',
        companyAddress: '企业地址',
        authenticationStatus: '认证状态',
        status: '账户状态',
        createTime: '创建时间'
      },
      formTheadWidth: {
        merchantId: '160',
        platformId: '160',
        merchantName: '110',
        owner: '129',
        thirdNo: '110',
        merType: '110',
        phone: '110',
        companyAddress: '110',
        authenticationStatus: '130',
        status: '110',
        createTime: '160'
      },
      form: {},
      checkList: ['merchantId', 'platformId', 'merchantName', 'owner', 'thirdNo', 'merType', 'phone', 'companyAddress', 'authenticationStatus', 'status', 'createTime'],
      formThead: ['merchantId', 'platformId', 'merchantName', 'owner', 'thirdNo', 'merType', 'phone', 'companyAddress', 'authenticationStatus', 'status', 'createTime'],
      list: null,
      selectTypeOptions: [],
      selectStatusOptions: [],
      total: null,
      listLoading: true,
      dialogFormVisible: false,
      dialogSelectTableVisible: false,
      dialogStatus: '',
      parentVisible: false,
      merchantManager_btn_add: false,
      merchantManager_btn_update: false,
      merchantManager_btn_del: false,
      commonMerchant: [],
      areaList: [],
      areaQuery: {
        areaCode: undefined
      },
      textMap: {
        create: '添加',
        update: '修改'
      },
      cardTypeOptions: [{
        value: '0',
        label: '身份证'
      }, {
        value: '1',
        label: '户口本'
      }, {
        value: '2',
        label: '护照'
      }, {
        value: '3',
        label: '军官证'
      }, {
        value: '4',
        label: '士兵证'
      }, {
        value: '5',
        label: '港澳居民往来内地通行证'
      }, {
        value: '6',
        label: '台湾通报往来内地通行证'
      }, {
        value: '7',
        label: '临时身份证'
      }, {
        value: '8',
        label: '外国人居留证'
      }, {
        value: '9',
        label: '警官证'
      }, {
        value: 'x',
        label: '其他证件'
      }],
      merTypeOptions: [
        {
          value: '00',
          label: '普通商户'
        }, {
          value: '01',
          label: '子商户'
        }
      ],
      tableKey: 0,
      formLabelWidth: '120px',
      rules: {
        merchantName: [
          {
            required: true,
            message: '请输入商户名称',
            trigger: 'blur'
          }
        ],
        companyName: [
          {
            required: true,
            message: '请输入企业名称',
            trigger: 'blur'
          }
        ],
        businessScope: [
          {
            required: true,
            message: '请输入经营范围',
            trigger: 'blur'
          }
        ],
        businessNo: [
          {
            required: true,
            message: '请输入工商注册号',
            trigger: 'blur'
          },
          {
            min: 10,
            max: 32,
            message: '长度在 10 到 32 个字符',
            trigger: 'blur'
          }
        ],
        legalPersonName: [
          {
            required: true,
            message: '请选择法人姓名',
            trigger: 'blur'
          }
        ],
        legalPersonCredType: [
          {
            required: true,
            message: '请选择法人证件类型',
            trigger: 'blur'
          }
        ],
        legalPersonCredNo: [
          {
            required: true,
            message: '请输入法人证件号码',
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入联系电话',
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入企业座机',
            trigger: 'blur'
          }
        ],
        fax: [
          {
            required: true,
            message: '请输入企业传真',
            trigger: 'blur'
          }
        ],
        httpAddress: [
          {
            required: true,
            message: '请输入企业网址',
            trigger: 'blur'
          }
        ],
        registeredCapital: [
          {
            required: true,
            message: '请输入注册资金',
            trigger: 'blur'
          }
        ],
        companyAddress: [
          {
            required: true,
            message: '请输入企业地址',
            trigger: 'blur'
          }
        // ],
        // businessLicence: [
        //   {
        //     required: true,
        //     message: '请上传营业执照',
        //     trigger: 'blur'
        //   }
        ]
      }
    }
  },
  created() {
    this.queryObj()
    this.getList()
    this.getAreas()
    this.merchantManager_btn_add = this.elements['merchantManager:btn_add']
    this.merchantManager_btn_update = this.elements['merchantManager:btn_update']
    this.merchantManager_btn_del = this.elements['merchantManager:btn_del']
  },
  computed: {
    ...mapGetters([
      'elements',
      'name',
      'userType',
      'userId',
      'token'
    ])
  },
  watch: {
    checkList(valArr) {
      this.formThead = this.checkList.filter(i => valArr.indexOf(i) >= 0)
      this.key = this.key + 1// 为了保证table 每次都会重渲 In order to ensure the table will be re-rendered each time
    }
  },
  methods: {
    handleSelectArea(val) {
      this.form.province = val[0]
      this.form.city = val[1]
      this.form.county = val[2]
    },
    getAreas() {
      fetchArea(this.areaQuery).then(response => {
        this.areaList = response
      })
    },
    handleClose(done) {
      this.listLoading = true
      this.addOrUpdate.platformId = this.platformId
      this.addOrUpdate.userId = this.userId
      this.addOrUpdate.columns = this.checkList.join(',')
      addOrUpdate(this.addOrUpdate)
        .then(response => {
          this.listLoading = false
          console.log('成功000000000000000000000000000')
        })
      done()
    },
    queryObj() {
      this.listLoading = true
      this.queryObjdata.platformId = this.platformId
      this.queryObjdata.userId = this.userId
      queryObj(this.queryObjdata)
        .then(response => {
          if (response.code === '0000') {
            console.log(response.baseUserTableField)
            if (response.baseUserTableField !== null && response.baseUserTableField !== '' && response.baseUserTableField !== undefined) {
              var showColumnsStr = response.baseUserTableField.columns
              if (showColumnsStr.length !== 0) {
                this.checkList = showColumnsStr.split(',')
                this.formThead = showColumnsStr.split(',')
              }
            }
          }
          this.listLoading = false
        })
    },
    getList() {
      this.listLoading = true
      this.listQuery.platformId = this.platformId
      if (this.userType === 4) {
        this.listQuery.owner = this.userId
      }
      page(this.listQuery)
        .then(response => {
          console.log('-----000000000---------')
          this.list = response.body.data.rows
          this.total = response.body.data.total
          this.listLoading = false
        })
    },
    merTypeChange(value) {
      console.log('-----------------------------')
      console.log(value)
      if (value === '01') {
        this.parentVisible = true
        var listQuerys = {
          page: 1,
          limit: 9999,
          merType: '00'
        }
        page(listQuerys)
          .then(response => {
            console.log('==========-------------------=')
            console.log(response)
            this.commonMerchant = response.body.data.rows
          })
      } else {
        this.parentVisible = false
        this.form.parentMerId = ''
      }
    },
    handleCreate() {
      this.form = {}
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleCreateSecect() {
      this.form = {}
      this.dialogStatus = 'Secect'
      this.dialogSelectTableVisible = true
    },
    handleUpdate(row) {
      this.form = row
      if (row.merType === '01') {
        this.parentVisible = true
        var listQuerys = {
          page: 1,
          limit: 9999,
          merType: '00'
        }
        page(listQuerys)
          .then(response => {
            console.log('==========-------------------=')
            console.log(response)
            this.commonMerchant = response.body.data.rows
          })
      }
      this.dialogFormVisible = true
      this.dialogStatus = 'update'
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delObj(row.id)
            .then(() => {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            })
        })
    },
    create(formName) {
      const set = this.$refs
      console.log('addObj=======================================================')
      this.form.owner = this.userId
      this.form.token = this.token
      set[formName].validate(valid => {
        if (valid) {
          addObj(this.form)
            .then(response => {
              if (response.code === '0000') {
                this.$notify({
                  title: '成功',
                  message: '添加成功',
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: '失败',
                  message: '添加失败',
                  type: 'fail',
                  duration: 2000
                })
              }
              this.dialogFormVisible = false
              this.getList()
            })
        } else {
          return false
        }
      })
    },
    update(formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          putObj(this.form.id, this.form).then(response => {
            if (response.body.code === '0000') {
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '失败',
                message: '修改失败',
                type: 'fail',
                duration: 2000
              })
            }
            this.dialogFormVisible = false
            this.getList()
          })
        } else {
          return false
        }
      })
    },

    handleFilter() {
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    // 营业执照
    upIdNegativeUrl: function() {
      document.getElementById('upload_idNegative').click()
    },
    upIdNegative(event) {
      if (event.target.files.length > 0) {
        this.file = event.target.files[0] // 提交的图片
        console.log(this.file)
        const param = new FormData() // 创建form对象
        param.append('file', this.file)
        const instance = axios.create({
          withCredentials: true
        })
        const config = {
          headers: { 'Content-Type': 'multipart/form-data', 'Authorization': getToken() }
        }
        instance.post('/api/crm/upload/file', param, config)
          .then(response => {
            console.log(response.body.data)
            this.form.businessLicence = response.body.data.filePath
          })
      }
    },
    merchantDetail(row) {
      this.$router.push({ path: '/customerManager/merchantBaseDetail', query: { row: row }})
    }
  }
}
</script>
<style scoped>
.imgSrc {
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
</style>
